// pages/login/wechatLogin.js
var app = getApp()
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad() {
    // 查看是否授权 
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
  getUserInfo(e) {
    var userInfo = e.detail.userInfo
    var data = {}
    if (typeof (userInfo) == 'undefined'){
      console.log("用户取消授权")
      data = { openId: app.openId}
    }else{
      data = {
        openId: app.openId,
        nickName: userInfo.nickName,
        icon: userInfo.avatarUrl,
        gender: userInfo.gender
      }
    }
    //注册
    wx.request({
      url: app.host + '/wechat/register',
      data: data,
      method:'post',
      complete: function (res) {
        console.log(res)
        if(res.data.code == 0){
          //注册成功
          wx.setStorageSync('accessToken', res.data.accessToken);
          app.defaultHeader.accessToken = res.data.accessToken
          app.accessToken = res.data.accessToken
          wx.setStorageSync('userInfo', res.data.userInfo);
          app.userInfo = res.data.userInfo
          wx.reLaunch({
            url: '/pages/userInfo/update/update',
          })
        }
      }
    })
    //跳转回首页
    wx.reLaunch({
      url: '/pages/index/index',
    })
  }
})